package 练习11_线程池综合使用案例;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: ThreadPoolStudy01
 * @Author: AllenSun
 * @Date: 2025/10/23 23:17
 */
public class ThreadPoolStudy03_future {
    public static void main(String[] args) {
        UserAccount zhangsan = new UserAccount("张三",100);
        UserAccount lisi = new UserAccount("李四",0);

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        double amount = 1;

        List<Future> futureResultList = new ArrayList<>();

        for (int i = 0; i < 103; i++) {

            Future<?> transferResult = executorService.submit(() -> {
                String transferresult = null;
                try {
                    transferresult = transfer03(zhangsan, lisi, amount);
                    return transferresult;
                } catch (Exception e) {
                    System.out.println("捕捉到报错信息：" + e.getMessage());
                    throw new RuntimeException(e);
                }
            });
            futureResultList.add(transferResult);

        }
        // 关闭线程池，不再接受新任务
        executorService.shutdown();
        // 顺序处理结果
        for (Future futureResult : futureResultList) {
            // 打印的结果是无顺序的
            boolean isDone = futureResult.isDone();
            System.out.println("线程是否执行完毕："+isDone);
            try {
                String result = futureResult.get().toString();
                System.out.println("线程执行结果："+result);
            } catch (Exception e) {
                System.out.println("处理结果时发生异常：" + e.getMessage());
            }
        }
        // 等待所有任务结束再退出主程序
        try {
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
        }
    }

    public static String transfer03(UserAccount from,UserAccount to,double amount) throws InterruptedException {
        synchronized (UserAccount.class) {
            double fromBalance = from.getBalance();
            double toBalance = to.getBalance();
            String result = "";
            if (fromBalance >= amount) {
                from.setBalance(fromBalance - amount);
                Thread.sleep(100);
                to.setBalance(toBalance + amount);
                result = "当前线程："+Thread.currentThread().getName()+"；转出账户：" + from.getUserName() + "，余额：" + from.getBalance()+"；转入账户：" + to.getUserName() +
                        "，余额：" + to.getBalance();
            } else {
                result = "当前线程："+Thread.currentThread().getName()+"；余额不足";
                throw new RuntimeException("抛出异常余额不足");
            }
            return result;
        }
    }
}
